package com.java1412.config;

import com.java1412.interceptor.AdminLoginInterceptor;
import com.java1412.interceptor.ApiLoginInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 自定义mvc的配置类
 *
 * @author java1412
 * @since 2023-08-07 15:46:07
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Resource
    private AdminLoginInterceptor adminLoginInterceptor;

    @Resource
    private ApiLoginInterceptor apiLoginInterceptor;

    // addInterceptors添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // ==============================后台接口的拦截器======================================
        // addInterceptor()添加自定义的拦截器
        registry.addInterceptor(adminLoginInterceptor)
                // 对/**路径拦截，其实就是所有请求路径
                .addPathPatterns("/admin/**")
                // 去掉登录接口不进行拦截
                .excludePathPatterns("/admin/user/login");

        // ==============================前台接口的拦截器======================================
        registry.addInterceptor(apiLoginInterceptor)
                .addPathPatterns("/api/**")
                // 登录接口需要剔除
                .excludePathPatterns("/api/user/login", "/alipay/**");
    }

    // 借助过滤器链条来完成跨域操作
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(-1);
        return registrationBean;
    }
}
